﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MetadataBasedConfigArch.Framework.Model;
using System.ComponentModel;

namespace MetadataBasedConfigArch.Framework.Validator
{
    public class DataTypePropertyValidator:IConfigInfoPropertyValidator
    {
        public bool IsValid(IConfigMetaConfigInfoProperty configInfoProperty, IConfigMetaConfigData configData)
        {
            String dataTypeName = configInfoProperty.Value;
            if (!String.IsNullOrEmpty(dataTypeName))
            {
                Type dataType = Type.GetType(dataTypeName);
                if (dataType != null)
                {
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(dataType);
                    if (typeConverter.CanConvertFrom(typeof(string)))
                    {
                        return typeConverter.ConvertFromString(configData.Value) != null;
                    }
                }
            }
            return false;
        }


        public bool CanBeAssignableFrom(IConfigMetaConfigInfoProperty configInfoProperty, object value)
        {
            String dataTypeName = configInfoProperty.Value;
            if (!String.IsNullOrEmpty(dataTypeName))
            {
                  Type dataType = Type.GetType(dataTypeName);
                  if (dataType != null)
                  {
                      return dataType.IsAssignableFrom(value.GetType());
                  }
            }
            return false;
        }
    }
}
